package com.spring.security.app.oauth2;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Collections;

/**
 * @author seabed_moon
 */
public class Oauth2Util extends OAuth2Utils {


    /**
     * 构建 OAuth2AccessToken
     *
     * @param authorizationServerTokenServices authorizationServerTokenServices
     * @param authentication                   authentication
     * @param clientId                         clientId
     * @param clientDetails                    clientDetails
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     */
    public static OAuth2AccessToken buildOauth2AccessToken(AuthorizationServerTokenServices authorizationServerTokenServices, Authentication authentication, String clientId, ClientDetails clientDetails) {
        // ~ 构建 自定义tokenRequest
        TokenRequest tokenRequest = new TokenRequest(Collections.emptyMap(), clientId, clientDetails.getScope(), "custom");
        // ~ 构建 oAuth2Request
        OAuth2Request refreshOauth2Request = tokenRequest.createOAuth2Request(clientDetails);
        // ~ 构建 oAuth2Authentication
        OAuth2Authentication refreshOauth2Authentication = new OAuth2Authentication(refreshOauth2Request, authentication);
        // ~ 构建 accessToken
        return authorizationServerTokenServices.createAccessToken(refreshOauth2Authentication);
    }

    /**
     * 默认的 ClientDetails
     *
     * @param clientId clientId
     * @return org.springframework.security.oauth2.provider.ClientDetails
     */
    public static ClientDetails buildPcClientDetails(String clientId) {
        ClientDetails clientDetails;
        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setClientId(clientId);
        clientDetails = baseClientDetails;
        return clientDetails;
    }

    /**
     * 默认的 ClientDetails
     *
     * @param clientId clientId
     * @return org.springframework.security.oauth2.provider.ClientDetails
     */
    public static ClientDetails buildAppClientDetails(String clientId) {
        ClientDetails clientDetails;
        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setClientId(clientId);
        clientDetails = baseClientDetails;
        return clientDetails;
    }

}
